const express = require('express');
//md5加密
const crypto = require('crypto');

const fs = require('fs');

//node url模块引入处理url
const url = require('url');
//解析url
const querystring = require('querystring');
//使用mongodb递增索引查数据
const ObjectID = require('mongodb').ObjectID;
const User = require("../models/user");
const Post = require('../models/post');
const router = express.Router();

var upload = require('./fileupload');

var getFiles = require('./getfile');

//github登录
const passport = require("passport");

router.get("/login/github",passport.authenticate("github",{session:false}));
router.get("/login/github/callback",passport.authenticate("github",{
    session:false,
    failureRedirect:'/login',
    successFlash:'登录成功?'
}),function(req,res){
    console.log(req)
    req.session.user = {
        name:req.user.username,
        head:req.user._json.avatar_url
    };
    res.redirect("/");
})

/* GET home page. */
router.get('/', function(req, res) {
    var page = req.query.p?parseInt(req.query.p):1;
    Post.getTen({pub:1}, page,function(err, posts,total) {
        if (err) {
            posts = [];
        }
        res.render('index', {
            title: '码咯-首页',
            user: req.session.user,
            page:page,
            total:total,
            isFirstPage:(page-1) ==0,
            isLastPage:((page-1)*10 + posts.length) == total,
            posts: posts,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});

router.get('/search', function(req, res) {
    let kw = req.query.q;
    let page = req.query.p?parseInt(req.query.p):1;
    console.log(new RegExp(kw))
    Post.getTen({$or: [{"title":new RegExp(kw)},{"post":new RegExp(kw)}],"pub":1}, page,function(err, posts,total) {
        if (err) {
            posts = [];
        }
        res.render('search', {
            title: '搜索页面',
            user: req.session.user,
            page:page,
            total:total,
            keyword:kw,
            isFirstPage:(page-1) ==0,
            isLastPage:((page-1)*10 + posts.length) == total,
            posts: posts,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});

router.get('/u/:name', checkLogin);
router.get('/u/:name', function(req, res) {
    User.get(req.params.name,function(err,user){
        if(!user){
            req.flash('error','用户不存在');
            return res.redirect('/')
        }
        // console.log(user.name)
        Post.get({name:user.name}, function(err, posts) {
        if (err) {
            req.flash('error', err);
            return res.redirect('/');
        }
        res.render('user_article', {
            title: user.name,
            user: req.session.user,
            posts: posts,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
        
    })
});

// router.get('/users', function(req, res) {

//     res.send('3333');

// });
router.post('/iLike', function(req, res) {

    if(req.session.user == null){
        res.json({ code: -2 , msg: "未登录" })
        return false;
    }
    
    let uid = req.session.user._id
    let aid = JSON.parse(req.body.data).aid
    User.setLike({ "uid": ObjectID(uid),"aid":aid},function(err,likes){
        if (err) {
            posts = [];
            res.json({ code: -1, msg: "服务器错误" })
            return false;
        }
        if(likes){
            res.json({ code: 200, msg: "接口返回成功", status :1 });
        }
    });
    
});

router.get('/getArticle', function(req, res) {

    Post.get(null, function(err, posts) {
        if (err) {
            posts = [];
            res.json({ code: -1, msg: "服务器错误" })
        }
        if (posts.length) {
            res.json({ code: 200, msg: "接口返回成功", body: { posts: posts } });
        } else {
            res.json({ code: 0, msg: "暂无数据", body: { posts: [] } });
        }
    });

});

router.get('/reg', checkNotLogin);
router.get('/reg', function(req, res) {
    res.render('reg', {
        title: '用户注册',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

router.post('/reg', checkNotLogin);
router.post('/reg', function(req, res) {
    var name = req.body.name,
        password = req.body.password,
        repassword = req.body.repassword;
    console.log(name, password, repassword)
    if(name == "" || password == ""){
        req.flash('error', '用户名和密码不能为空');
        return res.redirect('/reg'); //返回注册页
    }
    //检验用户两次输入的密码是否一致
    if (repassword != password) {
        req.flash('error', '两次输入的密码不一致!');
        console.log('两次输入的密码不一致')
        return res.redirect('/reg'); //返回注册页
    }
    //生成密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    var newUser = new User({
        name: name,
        password: password,
        email: req.body.email
    });
    //检查用户名是否已经存在 
    User.get(newUser.name, function(err, user) {
        console.log(err, user, 111)
        if (err) {
            console.log(err)
            req.flash('error', err);
            return res.redirect('/');
        }
        if (user) {
            req.flash('error', '用户已存在!');
            console.log("user is here")
            return res.redirect('/reg'); //返回注册页
        }
        //如果不存在则新增用户
        newUser.save(function(err, user) {
            console.log(err, user, 222)
            if (err) {
                console.log(err);
                req.flash('error', err);
                return res.redirect('/reg'); //注册失败返回主册页
            }
            req.session.user = newUser; //用户信息存入 session
            console.log("reg success")
            req.flash('success', '注册成功!');
            res.redirect('/'); //注册成功后返回主页
        });
    });
});

router.get('/login', checkNotLogin);
router.get('/login', function(req, res) {
    res.render('login', {
        title: '用户登录',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

router.post('/login', checkNotLogin);
router.post('/login', function(req, res) {
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    User.get(req.body.name, function(err, user) {
        if (!user) {
            req.flash('error', '用户不存在!');
            return res.redirect('/login');
        }
        if (user.password != password) {
            req.flash('error', '密码错误!');
            return res.redirect('/login');
        }
        req.session.user = user;
        req.flash('success', '登陆成功!');
        res.redirect('/');
    });
});

router.get('/post', checkLogin);
router.get('/post', function(req, res) {
    res.render('post', {
        title: '发表',
        user: req.session.user,
        type:0,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

router.get('/tools', function(req, res) {
    res.render('tools', {
        title: '工具',
        user: req.session.user
    });
});

router.post('/post', checkLogin);
router.post('/post', function(req, res) {
    var postCon = req.body.post.replace(/\<script.*?>.*?<\/script>/ig, '');
    var currentUser = req.session.user,
        post = new Post(currentUser.name, req.body.title, postCon,req.body.category,req.body.pub);
    post.save(function(err) {
        if (err) {
            req.flash('error', err);
            return res.redirect('/');
        }
        req.flash('success', '发布成功!');
        res.redirect('/'); //发表成功跳转到主页
    });
});

router.get('/detail/:id', function(req, res) {
    var id = req.params.id;

    Post.getOne({ "_id": ObjectID(id) }, function(err, post) {
        if (err) {
            post = {};
        }
        res.render('detail', {
            title: post.title,
            user: req.session.user,
            details: post,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});

router.get('/edit/:id', checkLogin);
router.get('/edit/:id', function(req, res) {
    var id = req.params.id;
    Post.edit({ "_id": ObjectID(id) }, function(err, post) {
        if (err) {
            post = {};
        }
        // console.log(post)
        res.render('edit', {
            title: '编辑文章',
            user: req.session.user,
            type:0,
            details: post,
            posthtml:post.phtml,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});

router.post('/edit/:id', checkLogin);
router.post('/edit/:id', function(req, res) {
    var id = req.params.id;
    var postCon = req.body.post.replace(/\<script.*?>.*?<\/script>/ig, '');
    Post.update({ "id": ObjectID(id),"title":req.body.title,"post":postCon,"pub":req.body.pub}, function(err) {
        if (err) {
            req.flash('error',err);
            return res.redirect('/')
        }
        req.flash('success','修改成功');
        res.redirect('/detail/'+req.params.id)
    });
});

router.get('/remove/:id', checkLogin);
router.get('/remove/:id', function(req, res) {

    var id = req.params.id;

    Post.remove({"id": ObjectID(id)}, function(err) {
        if (err) {
            req.flash('error',"err");
            return res.redirect('/')
        }
        req.flash('success','删除成功');
        res.redirect('back')
    });
});

router.get('/logout', checkLogin);
router.get('/logout', function(req, res) {
    req.session.user = null;
    req.flash('success', '登出成功1111!');
    res.redirect('/'); //登出成功后跳转到主页
});

router.get('/upload', checkLogin);
router.get('/upload', function(req, res) {
    res.render('upload', {
        title: '文件上传',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

router.post('/upload', checkLogin);
router.post('/upload', upload.single('file1'), function (req, res, next) {
    console.log(req.file)
    if(req.file){
        req.flash('success','上传成功')
    }else{
        req.flash('error','上传失败')
    }
    res.redirect('/upload')

});

router.get('/filelist', function(req, res) {
    var imgList = getFiles.getImageFiles("./public/");
    res.render('filelist', {
        title: '文件预览',
        user: req.session.user,
        imglists:imgList,
        host:req.host,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});


function checkLogin(req, res, next) {
    if (!req.session.user) {
        req.flash('error', '未登录!');
        return res.redirect('/login');
    }
    next();
}

function checkNotLogin(req, res, next) {
    if (req.session.user) {
        req.flash('error', '已登录!');
        return res.redirect('back');
    }
    next();
}

module.exports = router;